import os
import sys

import waflib.Logs

sys.path.append(os.path.abspath('waftools'))

import gitinfo

def options(opt):
    opt.load('compiler_c')
    opt.add_option('--board', action='store', default='snowy_bb',
                   help='Which board to build for '
                   '(snowy_bb|snowy_evt|snowy_evt2|spalding)',
                   choices=[ 'snowy_bb',
                             'snowy_bb2',  # Alias for snowy_evt2
                             'snowy_dvt',  # Alias for snowy_evt2
                             'snowy_s3',
                             'snowy_evt',
                             'snowy_evt2',
                             'spalding'])
    opt.add_option('--nowatchdog', action='store_true',
                   help='Do not enable watchdog timer or reset upon failure')
    opt.add_option('--loglevel', type='int', default=0,
                   help='Set the logging verbosity [default: %default]')
    opt.add_option('--big-bootloader', action='store_true',
                   help='Build for boards with an unprogrammed FPGA, loading '
                   'and launching firmware at 0x08010000')

def configure(conf):
    if conf.options.board in ('snowy_bb2', 'snowy_dvt', 'snowy_s3'):
        conf.options.board = 'snowy_evt2'

    CPU_FLAGS = [
        '-mcpu=cortex-m4', '-mthumb',
        '-mfpu=fpv4-sp-d16', '-mfloat-abi=softfp',
        ]
    OPT_FLAGS = [ '-Os' ,'-g' ]
    C_FLAGS = [
        '-std=c11', '-ffunction-sections',
        '-Wall', '-Wextra', '-Werror', '-Wpointer-arith',
        '-Wno-unused-parameter', '-Wno-missing-field-initializers',
        '-Wno-error=unused-function', '-Wno-error=unused-variable',
        '-Wno-error=unused-parameter', '-Wno-error=unused-but-set-variable',
        '-Wno-packed-bitfield-compat'
        ]

    conf.find_program('arm-none-eabi-gcc', var='CC', mandatory=True)
    conf.env.AS = conf.env.CC
    for tool in 'ar objcopy'.split():
        conf.find_program('arm-none-eabi-' + tool, var=tool.upper(),
                          mandatory=True)
    conf.env.BOARD = conf.options.board
    conf.env.MICRO_FAMILY = 'STM32F4'
    conf.env.append_unique('CFLAGS', CPU_FLAGS + OPT_FLAGS + C_FLAGS)
    conf.env.append_unique('DEFINES', [
        '_REENT_SMALL=1',
        'USE_STDPERIPH_DRIVER=1',
        'BOARD_' + conf.options.board.upper(),
        'MICRO_FAMILY_' + conf.env.MICRO_FAMILY,
        ])
    conf.env.append_unique('LINKFLAGS',
            ['-Wl,--cref', '-Wl,--gc-sections', '-specs=nano.specs']
            + CPU_FLAGS + OPT_FLAGS)

    if conf.options.nowatchdog:
        conf.env.append_unique('DEFINES', 'NO_WATCHDOG')

    if conf.options.loglevel >= 1:
        conf.env.append_unique('DEFINES', 'PBL_LOG_ENABLED')
    if conf.options.loglevel >= 2:
        conf.env.append_unique('DEFINES', 'VERBOSE_LOGGING')

    if conf.options.big_bootloader:
        conf.env.append_unique('DEFINES', 'BLANK_FPGA')
        conf.env.BOOTLOADER_LENGTH = '65536'
    else:
        conf.env.BOOTLOADER_LENGTH = '16384'
    conf.env.append_unique(
            'DEFINES', 'BOOTLOADER_LENGTH=' + conf.env.BOOTLOADER_LENGTH)

    conf.load('gcc gas objcopy ldscript')
    conf.load('binary_header')
    conf.load('file_name_c_define')

    conf.recurse('vendor')

def build(bld):
    if bld.cmd == 'install':
        raise Exception("install isn't a supported command. Did you mean flash?")

    linkflags = ['-Wl,-Map,snowy_boot.map']
    sources = (
            bld.path.ant_glob('src/*.S') + bld.path.ant_glob('src/**/*.c') )


    bld(features='subst',
        source='src/git_version.auto.h.in',
        target='src/git_version.auto.h',
        **gitinfo.get_git_revision(bld))
    _generate_fpga_header(bld)
    bld.recurse('vendor')
    bld(features='subst',
        source='src/stm32f_flash_boot.ld.in',
        target='src/stm32f_flash_boot.ld')
    bld(features='c asm cprogram objcopy',
        source=sources,
        includes='src',
        target='snowy_boot.elf',
        ldscript='src/stm32f_flash_boot.ld',
        linkflags=linkflags,
        objcopy_bfdname='ihex',
        objcopy_target='snowy_boot.hex',
        use='stm32_stdlib')

def _generate_fpga_header(bld):
    # This is temporary. The bootloader FPGA image will not need to be included
    # in the bootloader once it is burned into the FPGA's NVCM.
    if bld.env.BOARD in ('snowy_bb', 'snowy_evt'):
        fpga_src = 'snowy_bb1_boot.fpga'
    elif bld.env.BOARD in ('snowy_evt2',):
        fpga_src = 'snowy_boot.fpga'
    elif bld.env.BOARD in ('spalding',):
        fpga_src = 'spalding_boot.fpga'
    else:
        fpga_src = None

    if fpga_src:
        bld(features='binary_header',
            source='../' + fpga_src,
            target='src/drivers/display/bootloader_fpga_bitstream.auto.h',
            array_name='s_fpga_bitstream')

# vim:filetype=python
